package com.dkm.dkmproject.action;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.dkm.dkmproject.domain.OrderTb;
import com.dkm.dkmproject.domain.UserTb;
import com.dkm.dkmproject.domain.WalletTb;
import com.dkm.dkmproject.service.IOrderTbService;
import com.dkm.dkmproject.service.IUserTbService;
import com.dkm.dkmproject.service.IWalletTbService;
import com.dkm.dkmproject.utils.*;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author 刘梦祺
 * @since 2020-04-26
 */
@RestController
@Api(description = "订单接口文档")
@RequestMapping("/dkm.dkmproject/orderTb")
public class OrderTbController {
    Logger log = Logger.getLogger(
            OrderTbController.class.getName());

    @Resource
    private IOrderTbService iOrderTbService;

    @Resource
    FileTools fileTools;
    @Autowired
    IUserTbService userTbService;
    @Resource
    Tools tools;
    @Resource
    private Config config ;
    @Autowired
    IWalletTbService walletTbService;
    /**
     * 根据用户id查询订单
     *
     * @return
     */
    @ApiOperation(value = " 根据用户id查询订单", notes = "如果查询成功返回集合，失败返回为null")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "userId", value = "用户id"),
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "orState", value = "订单状态id"),
    })
    @ApiResponses({
            @ApiResponse(code = 401, message = "没有权限"),
            @ApiResponse(code = 403, message = "服务器拒绝请求"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对"),
            @ApiResponse(code = 500, message = "后台报错"),
            @ApiResponse(code = 200, message = "返回成功")
    })
    @GetMapping("/QueryOrder")
    public List<OrderTb>  QueryOrder(@RequestParam(value = "userId") Integer userId,@RequestParam(value = "orState") Integer orState){
        List<OrderTb> orderTbs=null;
        if(userId!=null){
            orderTbs  = iOrderTbService.QueryOrder(userId,orState);
        }
        return orderTbs;

    }

    /**
     * 增加订单的方法
     * @param orderTb 订单类
     * @return
     */
    @ApiOperation(value = " 增加订单的方法", notes = "成功则返回成功，否则返回失败")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "orId", value = "订单主键"),
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "scbId", value = "服务外键",required = true),
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "userId", value = "用户id",required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "orFile", value = "订单签字合同附件"),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "exp3", value = "购买次数",required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "orImg", value = "一次/一年 1为一次 2为一年",required = true),
            @ApiImplicitParam(paramType = "query", dataType = "BigDecimal", name = "orMoney", value = "总金额",required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "content", value = "合同内容",required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "bashName", value = "bash64的",required = true),
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "orState", value = "订单状态 1已签约,2待签约,3待支付",required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 401, message = "没有权限"),
            @ApiResponse(code = 403, message = "服务器拒绝请求"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对"),
            @ApiResponse(code = 500, message = "后台报错"),
            @ApiResponse(code = 200, message = "返回成功")
    })
    @PostMapping("/addOrderTb")
    @CrossOrigin
    public Message addOrderTb(@RequestBody OrderTb orderTb,HttpServletRequest request){
        orderTb.setOrState(2);
        Message message=new Message();
        log.info("=========================");
        log.info(orderTb.getOrContent()+"=="+orderTb.getOrImg()+"==="+orderTb.getUserId());
        /**
         * 下单类型 1为直接付款，2为拍照合同付款 3为合同付款
         */
        if(Integer.valueOf(orderTb.getOrContent())==1){
          log.info("1进来了======================"+orderTb.getOrPhone());
            OrderCodeFactory orderCodeFactory=new OrderCodeFactory();
            //传入订单号
            orderTb.setOrId(orderCodeFactory.getOrderCode(orderTb.getUserId().longValue()));
            int rows=iOrderTbService.insertSelective(orderTb);
            if(rows>0){
                message.setMsg("增加订单成功");
                //传入返回订单的id
                message.setNumone(orderTb.getOrId());
            }else{
                message.setMsg("失败");
                message.setNum(0);
            }
            return message;
        }else if(Integer.valueOf(orderTb.getOrContent())==2){
            log.info("1进来了======================"+orderTb.getOrPhone());
            if (orderTb.getFile2() != null && !"".equals(orderTb.getFile2().getOriginalFilename())) {
                String file1 = fileTools.saveFile("order", orderTb.getFile2());
                orderTb.setOrPhone(file1);
            }
            if (orderTb.getFile3() != null && !"".equals(orderTb.getFile3().getOriginalFilename())) {
                String file1 = fileTools.saveFile("order",orderTb.getFile3());
                orderTb.setOrNote(file1);
            }
            if (orderTb.getFile4() != null && !"".equals(orderTb.getFile4().getOriginalFilename())) {
                String file1 = fileTools.saveFile("order", orderTb.getFile4());
                orderTb.setExp1(file1);
            }
            OrderCodeFactory orderCodeFactory=new OrderCodeFactory();

            //传入订单号
            orderTb.setOrId(orderCodeFactory.getOrderCode(orderTb.getUserId().longValue()));
            log.info("1进来了======================"+orderTb.getUserId());
            int rows=iOrderTbService.insertSelective(orderTb);
            if(rows>0){
                log.info("1进来了======================"+orderTb.getOrId());
                //传入返回订单的id
                message.setNumone(orderTb.getOrId());
                message.setMsg("增加订单成功");
            }else{
                message.setMsg("失败");
                message.setNum(0);
            }
            return message;
        }else if(Integer.valueOf(orderTb.getOrContent())==3){

            EntityWrapper<UserTb> queryWrapper = new EntityWrapper();
            queryWrapper.eq("user_phone", orderTb.getPhoneTwo());
            log.info("3=================="+orderTb.getPhoneTwo());
            queryWrapper.eq("user_state", 1);
            List<UserTb> list = userTbService.selectList(queryWrapper);

            if (list.isEmpty()) {
                message.setNum(3);
                message.setMsg("该业务员电话不存在!");
                return message;
            }else{
                for (UserTb userTb : list) {
                    log.info("3=================="+userTb.getUserName());
                    orderTb.setOrFwname(userTb.getUserName());
                }
                //传入业务员电话
                orderTb.setOrPhoneOne(orderTb.getContactTwo());
                //传入业务员名字
            }
            //得到bash64成对象 得到签字的图片
            MultipartFile file=BASE64DecodedMultipartFile.base64ToMultipart(orderTb.getBashName());
            String path=fileTools.saveFile("order",file);
            log.info("3=================="+path);
            String content=PdfTools.pfdFile(orderTb);
            if(!StringUtils.isEmpty(path)){
                //http://192.168.10.123:8084/upload/order/2020-05/1590049525_mfba6rbg.png
                //生成一个订单号
                //OrderCodeFactory.getOrderCode(3L);
                OrderCodeFactory orderCodeFactory=new OrderCodeFactory();
                //传入订单号
                orderTb.setOrId(orderCodeFactory.getOrderCode(orderTb.getUserId().longValue()));
                String string=tools.getRandomString(10)+".pdf";
                //pdf 的文件路径
                String pdfUrl=config.getDir()+string;
                System.out.println("==-------------="+pdfUrl);
                orderTb.setOrFile(config.getPath()+""+string);
                orderTb.setOrNote(content);
                fileTools.addPdf(content,"https://www.mhdwx.com/"+path,pdfUrl);
                int rows=iOrderTbService.insertSelective(orderTb);
                if(rows>0){
                    message.setMsg("https://www.mhdwx.com/upload/"+string);
                    message.setNumone(orderTb.getOrId());
                    message.setNum(1);
                }else{
                    System.out.println("没进来"+orderTb);
                    message.setMsg("失败");
                    message.setNum(0);
                }
                return message;
            }
        }
        return null;
    }
    @GetMapping("get")
    public void get(){
        MultipartFile file= BASE64DecodedMultipartFile.base64ToMultipart("");
        if(file!=null){
            System.out.println("=====");
        }
        String path=fileTools.saveFile("order",file);
        System.out.println("=="+path);
    }
    @RequestMapping("selectAll")
    @ResponseBody
    public Map<String,Object> selectAll(@RequestParam("page") Integer pageNum ,@RequestParam("limit") Integer pageSize){
        Map<String,Object> map=new HashMap<>();

        map.put("code",0);
        map.put("msg","");
        map.put("data",iOrderTbService.selectAll(pageNum,pageSize));
        map.put("count",iOrderTbService.selectCountOne());
        return map;
    }

    @RequestMapping("selectAllThree")
    @ResponseBody
    public Map<String,Object> selectAllThree(@RequestParam("page") Integer pageNum ,@RequestParam("limit") Integer pageSize
    ,String orFwname){
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        List<OrderTb> list= iOrderTbService.selectAllTwo(pageNum,pageSize,orFwname);
        int count;
        if(list.size()!=0 &&list!=null){
            count=list.size();
        }else{
            count=0;
        }
        map.put("count",count);

        map.put("msg","");

        map.put("data",iOrderTbService.selectAllTwo(pageNum,pageSize,orFwname));
        return map;
    }
    @RequestMapping("findById")
    @ResponseBody
    public OrderTb findById(String orId){
        return iOrderTbService.selectByPrimaryKey(orId);
    }
    @RequestMapping("addorUpdate")
    @ResponseBody
    public Message addorUpdate(String orFwname, String orPhoneOne, BigDecimal scbMoney,String orId){
        System.out.println(orFwname+"===="+orPhoneOne+"===="+scbMoney+"===="+orId);
        Message message=new Message();
        //先查出业务人员的信息
        List<UserTb> list=userTbService.selectPhone(orPhoneOne,orFwname);


        if(list.size()!=0 &&list!=null){
            Integer userId=null;
            for (UserTb userTb : list) {
                userId=userTb.getUserId();
            }
            OrderTb orderTb=new OrderTb();
            orderTb.setOrId(orId);
            orderTb.setOrIsva(0);
            int rows=iOrderTbService.updateByPrimaryKeySelective(orderTb);
            if(rows>0){
                WalletTb walletTb=new WalletTb();
                walletTb.setUserId(userId);
                walletTb.setMoney(scbMoney);
                int rowsone=walletTbService.updateByPrimaryKeySelective(walletTb);
                if(rowsone>0){
                    message.setNum(1);
                    message.setMsg("操作成功");
                }else{
                    message.setNum(0);
                    message.setMsg("失败");
                }
            }else{
                message.setNum(0);
                message.setMsg("失败");
            }
        }else{
            message.setNum(0);
            message.setMsg("不是服务人员");
        }
        return message;
    }
    @RequestMapping("selectUserID")
    @ResponseBody
    public List<OrderTb> selectUserID(){
        List<OrderTb> orderTbList=new ArrayList<>();
        List<OrderTb> list=iOrderTbService.selectUserID();
        for (OrderTb orderTb : list) {
            String realname = orderTb.getWechatName();
            char[] r = realname.toCharArray();
            String realname1 =null;
            if(r.length ==1){ realname1 = realname; }
            if(r.length == 2){ realname1 = realname.replaceFirst(realname.substring(1),"*"); }
            if (r.length > 2) { realname1 = realname.replaceFirst(realname.substring(1,r.length-1) ,"*"); }
            orderTb.setWechatName(realname1);
            orderTb.setDateOne(tools.getTimeStr(orderTb.getOrFwphone()));
            orderTbList.add(orderTb);
        }
        return orderTbList;
    }
    @RequestMapping("selectSqCount")
    @ResponseBody
    public Message selectSqCount(String orId){
        Message message=new Message();
        int rows=iOrderTbService.selectSqCount(orId);
        if(rows>0){
            message.setNum(1);
        }else{
            message.setNum(0);
        }
        return message;
    }
    @RequestMapping("selectCount")
    @ResponseBody
    public int selectCount(String userId){
        List<UserTb> list=userTbService.selectUserId(Integer.valueOf(userId));
        for (UserTb userTb : list) {
            if(userTb.getUserState()==1){
                OrderTb orderTb=new OrderTb();
                orderTb.setOrFwname(userTb.getUserName());
                orderTb.setOrPhoneOne(userTb.getUserPhone());
                int count=iOrderTbService.selectCountTwo(orderTb);
                return count;
            }else{
                return 0;
            }
        }
        return 0;
    }
}
